#include "MyString.h"
#include <string.h>
#include <stdio.h>
void Initialize(MyString *obj, const char *str);
void Print(MyString *obj);
int Size(MyString *obj);
int IsEqual(MyString *obj1,MyString *obj2);
int IsContains(MyString *dest, MyString *src);
char* AtIndex(MyString *obj, int index);
void RemoveString(MyString *obj, const char* str);
void Insert(MyString *obj, const char* str, int index);
void Initialize(MyString *obj, const char *str)
{
    obj->size=strlen(str);
    strcpy(obj->string,str);

    //func init
    obj->print = Print;
    obj->Size = Size;
    obj->IsEqual = IsEqual;
    obj->AtIndex = AtIndex;
    obj->Insert = Insert;
    obj->IsContains = IsContains;
    obj->RemoveString = RemoveString;
}

void Print(MyString *obj)
{
    printf("%s\n",obj->string);
}

int Size(MyString *obj)
{
    return obj->size;
}
int IsEqual(MyString *obj1,MyString *obj2){
    if(strcmp(obj1->string,obj2->string) == 0){
        return 1;
    }else{
        return 0;
    }
}

int IsContains(MyString *dest, MyString *src)
{
    char *equal = strstr(dest->string,src->string);
    if(equal == NULL){
        return 0;
    }else{
        return 1;
    }
}

char* AtIndex(MyString *obj, int index)
{   
    if(index >= obj->size ||  index < 0)  
        return NULL;
    char *ptr = obj->string;
    while(index != 0){
        ptr++;
        index--;
    }
    return ptr;
}

void RemoveString(MyString *obj, const char *str)
{
    int i;
    char *start = strstr(obj->string,str);
    if(start == NULL){
        return NULL;
    }else{
        char *back = start+strlen(str);
        while (*back != '\0')
        {
            *start = *back;
            start++;
            back++;
        }
        *start = '\0';
        obj->size -= strlen(str);
        
    }
}

void Insert(MyString *obj, const char *str, int index)
{
    //int len = strlen(str);
    if(index < 0 || index > obj->size){
        return ;
    }
    else {

        char new_str[MAX]={0};
        strncpy(new_str,obj->string,index);
        strncpy(new_str+index,str,strlen(str));
        strcpy(new_str+index+strlen(str),obj->string+index);

        memset(obj->string,0,MAX);

        strcpy(obj->string,new_str);
        obj->size = strlen(obj->string);
    }

}
